package life.fairy.community.controller;

import life.fairy.community.dto.AccessTokenDTO;
import life.fairy.community.dto.GiteeUser;
import life.fairy.community.model.User;
import life.fairy.community.provider.GiteeProvider;
import life.fairy.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {

    @Autowired
    private GiteeProvider giteeProvider;

    /*
     *   @Value注解 通过${} 大括号中的key 从公共配置文件中获取指定key的value值，并放到private String clientId变量中
     */
    @Value("${gitee.client.id}")
    private String clientId;

    @Value("${gitee.client.secret}")
    private String clientSecret;

    @Value("${gitee.redirect.uri}")
    private String redirectUri;

    @Autowired
    private UserService userService;

    /*
     * callback函数作为 gitee 认证的回调函数，进行code 和 state 参数的获取
     * 函数中，传递的HttpServletRequest request 是将请求/callback接口的请求对应的请求体拿到，可以通过request对象获取请求对象携带的信息
     * 函数中的HttpServletResponse response 获取该callback接口响应值，用于对调用结果进行处理
     */
    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        // 利用回调函数，对accessToken赋值
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);// 使用accessTokenDTO值，得到accessToken值
        GiteeUser giteeUser = giteeProvider.getUser(accessToken);// 获取 giteeUser json信息
        if (giteeUser != null && giteeUser.getId() != null) { // 判断获取的 giteeUser 信息是否为空
            // 封装User实体的各个字段值
            User user = new User();
            String token = UUID.randomUUID().toString(); // 生成token持久化保存，及时网站重启启动不影响用户登录状态
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            response.addCookie(new Cookie("token", token));
            return "redirect:/";

        } else {
            // 登录失败，重新登录
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
